package com.dgut.usermodule.log;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.dgut.usermodule.dao.LogJpaRepository;
import com.dgut.usermodule.entity.Log;
@Aspect
@Component
public class LogAspect {
	@Autowired
	private LogJpaRepository dao;
	/**
	 * 每次执行service层的操作，自动将操作写入日志
	 * @param joinPoint
	 */
	@After("execution(* com.dgut.*.web.*.*(..))")
	public void loginLog(JoinPoint joinPoint) {
		if (getUsername()==null) {
			return;
		}
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		String[] params = signature.getParameterNames();
		Log log = new Log();
		if(params!=null) {
			String param = "";
			for(String p:params) {
	        	param = param+p+" ";
	        }
			if(param!="") {
				log.setParams(param);
			}
		}
		log.setUserName(getUsername());
		log.setModuleName(joinPoint.getTarget().getClass().getName().split("\\.")[2]);
		log.setDate(new Date());
		log.setOperate(method.getName());
		log.setIp(request.getRemoteAddr());
		dao.save(log);
	}
	public String getUsername() {
		return (String) SecurityUtils.getSubject().getPrincipal();
	}
}
